﻿using System;
using System.Reflection;
using UnityEngine;

namespace TC
{
    public class ValueInput<T> : ValuePort
    {
        public override Type type => typeof(T);
        public override bool IsInput => true;
        public override bool AllowMultiConnect => false;

        public T defaultValue = default;
        public T Value
        {
            get
            {
                //这里应该返回的是与它相连的Output Value
                ValueOutput<T> tmp = parent.graph.GetConnectPort<ValueOutput<T>>(this);
                if(tmp != null)
                {
                    return tmp.Value;
                }
                return defaultValue;
            }
        }
        
        public ValueInput(FlowNode parent, string name) : base(parent, name)
        {
        }

        public override bool CanConnect(Port other)
        {
            if (!other.IsInput && type.IsAssignableFrom(other.type))
            {
                return true;
            }
            return false;
        }

        public override bool CanConnect(Type nodeType, out FieldInfo portInfo)
        {
            var fields = nodeType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (var field in fields)
            {
                if (field.FieldType == typeof(ValueOutput<T>))
                {
                    portInfo = field;
                    return true;
                }
            }
            portInfo = default;
            return false;
        }

        public override void OnSerialize_t(ISerializeEntity entity)
        {
            base.OnSerialize_t(entity);

            Port_entity p = entity as Port_entity;
            p.name = name;
            p.defaultValue = defaultValue;
        }

        public override void OnDeserialize_t(ISerializeEntity entity)
        {
            base.OnDeserialize_t(entity);

            Port_entity p = entity as Port_entity;
            name = p.name;
            defaultValue = (T)p.defaultValue;
        }

        public override ISerializeEntity CreateEntity()
        {
            if(typeof(T).IsValueType)
                return new Port_entity();
            return null;
        }
    }
}
